package com.kingdee.shr.ques.cloud.poi.utils;

import com.kingdee.shr.ques.cloud.base.exception.BusinessException;
import com.kingdee.shr.ques.cloud.base.exception.ExceptionConst;
import com.kingdee.shr.ques.cloud.poi.entity.ExcelDetail;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Miaoxiong Fan
 * @description poi通用工具类
 * @data 2019/2/25
 */
public class PoiCommonUtil {

    /**
     * @author Miaoxiong Fan
     * @description 获取导入Excel文件信息
     * date 2019/2/25
     * @return [{"fileIndex":0,"total":1000,"success":0,"failure":0}]
     */
    public static List<ExcelDetail> getExcelDetail(MultipartFile[] file , int beginReadRowIndex) {
        List<ExcelDetail> result = new ArrayList<>();
        ExcelDetail excelDetail = null;
        for(int i=0; i<file.length; i++) {
            String filename = file[i].getOriginalFilename();
            if (!filename.matches("^.+\\.(?i)(xlsx)$")) {
                throw new BusinessException(ExceptionConst.IMPORT_FAILURE , "文件格式不正确，请导入xlsx后缀文件");
            }
            try {
                XSSFWorkbook template = new XSSFWorkbook(file[i].getInputStream());
                SXSSFWorkbook workbook = new SXSSFWorkbook(template);
                int totalRows = workbook.getXSSFWorkbook().getSheetAt(0).getPhysicalNumberOfRows();
                excelDetail = new ExcelDetail(i , totalRows - beginReadRowIndex);
                result.add(excelDetail);
            } catch (IOException e) {
                throw new BusinessException(ExceptionConst.IMPORT_FAILURE , "文件格式不正确，解析出错！");
            }
        }
        return result;
    }

    public static void process(ExcelDetail excelDetail, List<Integer> successProcess, List<Integer> failureProcess) {
        excelDetail.incFailure(failureProcess.size());
        excelDetail.incSuccess(successProcess.size());
        successProcess.clear();
        failureProcess.clear();
    }
}
